package com.example.hangzhou.welbeing.mytestdemoapp.utils;

import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hangzhou.welbeing.mytestdemoapp.R;

/**
 * 杭州惟君医疗科技有限公司09
 * Created by 20433 on 2018/5/16
 *
 * @desc 东风山河绿，春已不折柳，繁花看不尽，处处惹人留
 * @desc 佛祖镇楼，bug辟容易
 */

public class ToastUtil {

    private Toast mToast;
    private Handler mHandler = new Handler();
    private String message;
    private final TextView mTextView;
    private boolean canceled = true;
    private TimeCount timeCount;

    public ToastUtil(Context mcontext,int layoutId,String msg) {
        message = msg;
        LayoutInflater inflater =   (LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //自定义布局
       View view =  inflater.inflate(layoutId,null);

        //自定义toast文本
        mTextView = (TextView)view.findViewById(R.id.toast_msg);
        mTextView.setText(msg);
        if(mToast == null){
            mToast = new Toast(mcontext);
        }
        mToast.setGravity(Gravity.CENTER,0,0);
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.setView(view);
    }
    /**
     * 自定义居中显示toast
     */
    public void show(){
        mToast.show();
    }

    /**
     * 自定义时长、居中显示toast
     * @param duration
     */
    public void show(int duration){
        timeCount = new TimeCount(duration,5000);

        if(canceled){
            timeCount.start();
            canceled =false;
            showUntilCancel();

        }
    }
    /**
     * 隐藏toast
     */

    private void hide(){
        if(mToast != null){
            mToast.cancel();
        }
        canceled = true;
    }
    private void showUntilCancel() {
        //如果已经取消显示，就直接return
        if(canceled){
            return;
        }
        mToast.show();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showUntilCancel();
            }
        },Toast.LENGTH_LONG);
    }

    private class TimeCount extends CountDownTimer {
//millisInFuture总计时长，countDownInterval时间间隔(一般为1000ms)
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTextView.setText(message+";"+millisUntilFinished/1000+"s 后消失");
        }

        @Override
        public void onFinish() {
                hide();
        }
    }
}
